package com.peanut.baby.mvp.web;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import androidx.annotation.Nullable;

import com.peanut.baby.R;
import com.peanut.baby.comm.BaseDialog;
import com.peanut.baby.http.HttpConfig;
import com.peanut.baby.mvp.BaseMvpActivity;
import com.peanut.baby.mvp.web.x5.X5WebViewActivity;
import com.peanut.baby.util.ShareUtil;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.widget.TitleLayout;
import com.tencent.mars.xlog.Log;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by anonymouslystudio on 2017/8/9.
 */

public class WebViewActivity extends BaseMvpActivity implements TitleLayout.OnTitleClickListener{
    private static final String TAG = WebViewActivity.class.getSimpleName();
    @BindView(R.id.title)
    TitleLayout title;
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.webview_progress)
    ProgressBar progressBar;

    private String url, titleStr;

    public static void start(Context ctx, String url, String title,String imgUrl) {
        X5WebViewActivity.start(ctx,url,title,imgUrl);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        ButterKnife.bind(this);
        url = getIntent().getStringExtra("url");
        titleStr = getIntent().getStringExtra("title");
        initView();

    }

    /**
     *
     */
    private void initView() {
        title.setOnTitleClickedListener(this);
        title.setTitle(StringUtil.isNullOrEmpty(titleStr)? "详情":titleStr);
        title.setTitleBackVisibility(true);
        if(url.equals(HttpConfig.WIKI_URL)){
            title.setTitleRightTextDrawable("", R.drawable.icon_share);
            title.setTitleRightVisibility(true);
        }

        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(false);
        settings.setUseWideViewPort(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        //
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        //
        settings.setDomStorageEnabled(true);


        webView.setWebChromeClient(new MyWebChromeClient());
        webView.setWebViewClient(new MyWebClient());
        webView.setDownloadListener(new MyDownloadListener());

        webView.loadUrl(url);
    }

    @Override
    public void onTitleBackClicked() {
        if(webView.canGoBack()){
            webView.goBack();
        }else{
            finish();
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(webView.canGoBack()){
                webView.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onTitleRightClicked() {
        Log.d("X5","webview share clicked");
        new BaseDialog().showShareDialog(WebViewActivity.this, new BaseDialog.OnShareItemSelected() {
            @Override
            public void onShareItemSelected(int item) {
                String platName = "";
                if(item == BaseDialog.OnShareItemSelected.TYPE_MOMENT){
                    platName = WechatMoments.NAME;
                }else if(item == BaseDialog.OnShareItemSelected.TYPE_WEIXIN){
                    platName = Wechat.NAME;
                }else if(item == BaseDialog.OnShareItemSelected.TYPE_WEIBO){
                    platName = SinaWeibo.NAME;
                }else if(item == BaseDialog.OnShareItemSelected.TYPE_QQ){
                    platName = QQ.NAME;
                }
                if(StringUtil.isNullOrEmpty(platName)){
                    return;
                }
                ShareUtil.getInstance().share(titleStr,titleStr,url, platName,"", new ShareUtil.IShareCallback() {
                    @Override
                    public void onShareFinished(boolean isSuccess, String platformName, String failReason) {
                        showToast(isSuccess?"分享成功":failReason);

                    }
                });
            }
        });
    }

    @Override
    public void onTitleClicked() {

    }

    /**
     * webVIew设置进度条
     */
    class MyWebChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            progressBar.setProgress(newProgress);
        }

    }

    class MyWebClient extends WebViewClient {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressBar.setVisibility(View.GONE);


        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            Log.d(TAG,"onReceivedError->"+error.toString());
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
            Log.d(TAG,"onReceivedError->"+errorResponse.toString());
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, final String url) {
//            webView.loadUrl(url);
            return super.shouldOverrideUrlLoading(view,url);
        }

    }

    class MyDownloadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String arg0, String arg1, String arg2,
                                    String arg3, long arg4) {
            Uri uri = Uri.parse(arg0);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }

    }
}
